package com.atguigu.gulimallsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.es.SkuEsModel;
import com.atguigu.gulimallsearch.config.GulimallElasticSearchConfig;
import com.atguigu.gulimallsearch.constant.EsConstant;
import com.atguigu.gulimallsearch.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service("ProductSaveService")
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    RestHighLevelClient client;

    //上架,保存es数据
    @Override
    public void productStatusUp(List<SkuEsModel> esModels) throws Exception {
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel esModel : esModels) {
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.index(EsConstant.GULIMALL_PRODUCT_INDEX);
            indexRequest.id(esModel.getSkuId().toString());
            String string = JSON.toJSONString(esModel);
            indexRequest.source(string, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        //批量保存
        BulkResponse bulk = client.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);

        //如果批量插入错误,就抛异常
        if (bulk.hasFailures()){//有问题返回true
            throw new Exception("es批量保存异常");
        }
        //获取批量处理结果
        BulkItemResponse[] items = bulk.getItems();
        List<String> collect = Arrays.stream(items).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.info("商品上架成功id:{},返回数据:{}",collect,bulk.toString());

    }
}
